package com.yonyou.pmclouds.businessobject.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.view.DisableWrap;
import com.yonyou.pmclouds.businessobject.rmiitf.BusinessObjectMaintain;
import com.yonyou.pmclouds.print.rmiitf.PrintMaintain;
import com.yonyou.pmclouds.print.util.ParamMapUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/rest/print")
public class BusinessObjectMobileController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private BusinessObjectMaintain businessObjectMaintain;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private PrintMaintain printMaintain;

    @GetMapping("/getPrintCode")
    public String getPrintCodeByBO(@RequestParam("boCode") String boCode,
                                   @RequestParam("tenantId") String tenantId) throws BusinessException {
        return businessObjectMaintain.getPrintCode(boCode, tenantId);
    }

    @GetMapping(value = "/preview", produces = "application/json;charset=UTF-8")
    public void getPrintPreview(HttpServletResponse response, HttpServletRequest request) throws BusinessException{
        try {
            Map<String, String> paramMap = ParamMapUtil.getParameterMap(request.getParameterMap());
            String html = printMaintain.getPrintPreview(paramMap);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().print(html);
            response.flushBuffer();
        } catch (IOException e) {
            throw new BusinessException("get preview html : " + e.getMessage());
        }
    }

    @RequestMapping(value = {"/printdelegate"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @DisableWrap
    public String getPrintDelegate(HttpServletRequest request) throws BusinessException{
        try {
            Map<String, String> paramMap = ParamMapUtil.getParameterMap(request.getParameterMap());
            String method = request.getMethod();
            return printMaintain.getPrintDelegate(paramMap, method);
        } catch (Exception e) {
            throw new BusinessException("print delegate : " + e.getMessage());
        }
    }
}
